<template>
	<el-card>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="悬赏状态" prop="isReward">
        <el-select
          v-model="queryParams.isReward"
          placeholder="悬赏"
          clearable
          style="width: 200px"
        >
          <el-option
            label="悬赏"
            :value="true"
          ></el-option>
					<el-option
            label="不悬赏"
            :value="false"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="审核状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="审核通过"
          clearable
          style="width: 200px"
        >
          <el-option :value="1" label="待审核" />
          <el-option :value="2" label="审核通过" />
					<el-option :value="3" label="审核不通过" />
        </el-select>
      </el-form-item>
     
      <el-form-item>
        <el-button class="filter-item" type="primary" @click="getInfo">
          <i-ep-search />
          搜索
        </el-button>
        <!-- <el-button @click="getInfo"> <i-ep-refresh />重置 </el-button> -->
      </el-form-item>
    </el-form>
  </el-card>


  <div>
    <el-table :data="dataList" v-loading="loading" 
		:header-cell-style="{'text-align':'center'}"
    :cell-style="{'text-align':'center'}"
		style="width: 100%">
      <!-- <el-table-column prop="id" label="序号" width="120" /> -->
			<!-- <el-table-column  label="序号" width="100">
    			<template #default="scope">
					   <span>{{scope.$index+1}}</span>
     			 </template>
   			 </el-table-column> -->
					<el-table-column
                fixed
                type="index"
                :index="indexMethod"
                label="序号"
                width="70"
              />
      <el-table-column prop="title" label="标题" width="200" />
      <el-table-column prop="questionDescribe" label="问题描述" width="200"/>
      <el-table-column prop="authorUsername" label="作者" width="150"/>
			<el-table-column prop="isReward" label="悬赏状态" width="150"/>
      <el-table-column prop="status" label="审核状态" width="120">
        <template #default="scope">
          <span v-if="scope.row.status === 1">待审核</span>
          <span v-else-if="scope.row.status === 2">审核通过</span>
          <span v-else-if="scope.row.status === 3">内容违规</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="400">
        <template #default="scope">
          <!-- <el-button link type="primary" size="small">审核</el-button> -->
          <el-button type="success" @click="detailsClick(scope.row.id)"   v-hasPerm="['resource:question:get']">详情</el-button>
          <el-button type="danger" @click="deleteClick(scope.row.id)"   v-hasPerm="['resource:question:del']">删除</el-button>
					<el-button type="warning" @click="openDialog(scope.row.id)"  v-hasPerm="['resource:question:update']"
          >编辑</el-button>
          <el-button
            type="info"
            v-if="scope.row.status === 1"
            @click="handleClick(scope.row)"
            >审核</el-button
          >
        </template>
      </el-table-column>
    </el-table>

		 <!-- 分页搜索 -->
		 <div
              style="
                display: flex;
                justify-content: center;
                width: 100%;
                margin-top: 15px;
              "
            >
              <el-pagination
                background
                layout="sizes, prev,slot, next, jumper"
                :page-count="pageTotal"
                :page-sizes="[10, 20, 30, 50]"
                :current-page="activePager"
                @update:current-page="pageChange"
                @update:page-size="sizeChange"
                :default-current-page="1"
                :default-page-size="10"
              >
                <div class="pagination">
                  <span
                    class="pagination__item"
                    :class="{ active: activePager === pager }"
                    v-for="pager in pageArr"
                    :key="pager"
                    @click="pageChange(pager)"
                  >
                    {{ pager }}
                  </span>
                </div>
              </el-pagination>
            </div>
            <!-- 分页搜索 -->


<!-- 编辑弹窗-->
	<el-dialog v-model="editDialog.visible" title="编辑"  width="100%" @close="cloceEditDialog">
  <div class="box">
    <div class="main" v-loading="loading">
      <h1 class="title">编辑问答</h1>
      <el-form
        :model="questionDetail"
        :rules="rules"
        ref="ruleFormRef"
        label-width="52px"
        size="large"
        label-position="left"
      
        validate-on-rule-change
      >
        <el-form-item label="标题" prop="title" style="width: 100%">
          <el-input
            style="width: 100%"
            type="text"
            v-model="questionDetail.title"
            placeholder="请输入问题标题..."
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            v-model="questionDetail.questionDescribe"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <v-md-editor
            v-model="questionDetail.content"
            height="480px"
            placeholder="请输入内容"
            :disabled-menus="[]"
            @upload-image="handleUploadImage"
          ></v-md-editor>
        </el-form-item>
        <el-form-item label="状态" prop="isReward">
          <el-radio-group v-model="questionDetail.isReward">
            <el-radio :label="false">不悬赏</el-radio>
            <el-radio :label="true">悬赏</el-radio>
          </el-radio-group>
          <el-input-number
            v-if="questionDetail.isReward"
            v-model="questionDetail.rewardPoints"
            :min="0"
            :max="15"
            size="default"
            style="margin-left: 16px; width: 128px"
          />
        </el-form-item>
        <el-form-item>
          <div style="width: 100%; display: flex; justify-content: center">
            <el-button type="primary" round @click="update(questionDetail)">
              <el-icon>
                <Promotion />
              </el-icon>
              &nbsp;修改
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</el-dialog>


    <!-- 审核 -->
    <el-dialog v-model="questiondialog.visible" title="审核信息">
      <el-form :model="formData">
        <el-radio-group v-model="formData.status">
          <el-radio :label="2">审核通过</el-radio>
          <el-radio :label="3">内容违规</el-radio>
        </el-radio-group>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="questiondialog.visible = false">取消</el-button>
          <el-button type="primary" @click="axamineSubmit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="detaildialog.visible" title="详细信息" width="70%" top="5vh">
      <el-descriptions border class="px-32px" direction="vertical">
        <el-descriptions-item label="id">{{
          questionDetailData?.id
        }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{
          questionDetailData?.title
        }}</el-descriptions-item>
        <el-descriptions-item label="问题描述">{{
          questionDetailData?.questionDescribe
        }}</el-descriptions-item>
        <el-descriptions-item label="用户">{{
          questionDetailData?.authorUsername
        }}</el-descriptions-item>
        <el-descriptions-item label="赏贴">{{
          questionDetailData?.isReward
        }}</el-descriptions-item>
        <el-descriptions-item label="奖励分数">{{
          questionDetailData?.rewardPoints
        }}</el-descriptions-item>
        <el-descriptions-item label="奖励状态">{{
          questionDetailData?.status
        }}</el-descriptions-item>

        <el-descriptions-item label="管理员">{{
          questionDetailData?.managerUsername
        }}</el-descriptions-item>

        <el-descriptions-item label="状态">
          <span v-if="questionDetailData?.status === 1"
            ><el-tag type="info" size="large">待审核</el-tag></span
          >
          <span v-else-if="questionDetailData?.status === 2"
            ><el-tag type="success" size="large">审核通过</el-tag></span
          >
          <span v-else-if="questionDetailData?.status === 3"
            ><el-tag type="danger" size="large">内容违规</el-tag></span
          >
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ questionDetailData?.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ questionDetailData?.publishTime }}
        </el-descriptions-item>
      </el-descriptions>
      <v-md-preview :text="questionDetailData?.content"></v-md-preview>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
	getQuestion,
	exmineQuestion,
	deleteQuestion,
	detailQuestion, detailQuestionBack,
} from "@/api/question";
import { QuestionInfo, requestInfo } from "@/api/question/type";
import { computed, onMounted, reactive, ref } from "vue";
import { File_API } from '@/api/file'
import axios from 'axios'
import { editQuestion } from '@/api/question/index'
import { ElMessage, FormRules } from 'element-plus'
import {Promotion} from '@element-plus/icons-vue'


defineComponent({
  components: { 
		Promotion,
  },
});

const questionDetailData = ref<QuestionInfo>();

const loading = ref(true);
//审核弹框
const questiondialog = reactive<DialogOption>({
  visible: false,
});


//编辑弹框
const editDialog = reactive<DialogOption>({
  visible: false,
	title:''
});

const detaildialog = reactive<DialogOption>({
  visible: false,
});

const formData = reactive<QuestionInfo>({
  id: 0,
  title: "",
  questionDescribe: "",
  content: "",
  authorUsername: "",
  author: "",
  isReward: 0,
  rewardPoints: 0,
  rewardStatus: 0,
  createTime: "",
  status: 0,
  publishTime: "",
  managerUsername: "",
});

const dataList = ref<QuestionInfo[]>();

const queryParams = ref<requestInfo>({
  pageNum: 1,
  pageSize: 10,
  isReward: true,
  status: 2,
});



//总共页数
const pageTotal = ref(0);
//后端传来的页码数组
const pageArr = ref([]);
//当前页码
const activePager = ref(1);

const indexMethod = (index: number) => {
  return index + (activePager.value - 1) * queryParams.value.pageSize + 1;
};

const questionDetail = reactive<QuestionInfo>({
  id: 0,
  title: '',
  questionDescribe: '',
  content: '原始内容',
  authorUsername: '',
  author: '',
  isReward: false,
  rewardPoints: 0,
  rewardStatus: false,
  createTime: '',
  status: 0,
  publishTime: '',
	managerUsername: ''
})
// const userStore = useUserStore()
const ruleFormRef = ref()

const rules = reactive<FormRules>({
  title: [{ required: true, message: '请输入标题！', trigger: 'blur' }],
  content: [{ required: true, message: '请输入问题内容！', trigger: 'blur' }],
  isReward: [{ required: true, message: '请选择悬赏 状态！', trigger: 'blur' }],
})


//删除数据
async function deleteClick(id?: number) {
  await ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteQuestion(id).then(() => {
      ElMessage.success("删除成功");
      getInfo();
    });
  });
}

async function handleClick(row: QuestionInfo) {
  questiondialog.visible = true;
  await Object.assign(formData, row);
  console.log(formData.id);
  console.log(formData.status);
}


//打开编辑弹窗
async function openDialog(id: any) {
	await detailQuestion(id).then(({ data }) => {
    Object.assign(questionDetail, data);
	});
	// questionDetail.author = row.author;
	// questionDetail.authorUsername = row.authorUsername
	// questionDetail.content = row.content
	// questionDetail.createTime= row.createTime
	// questionDetail.id= row.id
	// questionDetail.status= row.status
	// questionDetail.rewardPoints= row.rewardPoints
	// questionDetail.rewardStatus= row.rewardStatus
	// questionDetail.managerUsername =  row.managerUsername
	// questionDetail.questionDescribe =  row.questionDescribe
	// questionDetail.publishTime =  row.publishTime
	// questionDetail.isReward =  row.isReward
	// questionDetail.title =  row.title
	editDialog.visible = true;
  editDialog.title = "编辑问答";
}

function cloceEditDialog() {
	editDialog.visible = false;
}


//详情
async function detailsClick(id: number) {
  questionDetailData.value = undefined;
  detaildialog.visible = true;
  await detailQuestionBack(id).then(({ data }) => {
    questionDetailData.value = data;
    console.log(1212);
    console.log(questionDetailData);
  });
}


//审核数据
async function axamineSubmit() {
  loading.value = true;

  console.log(formData.status);

  await exmineQuestion(formData.id, formData.status)
    .then(() => {
      ElMessage.success("审核成功");
      questiondialog.visible = false;
      getInfo();
    })
    .finally(() => (loading.value = false));
}

//获取数据
async function getInfo() {
  loading.value = true;
  await getQuestion(queryParams.value)
    .then((res) => {
      dataList.value = res.data.data;
			pageTotal.value = res.data.navigatepageNums[res.data.navigatepageNums.length - 1];
    pageArr.value = res.data.navigatepageNums;
			console.log("数据列表:", dataList.value);
    })
    .catch((error) => {
      console.error("Error:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  getInfo();
});


async function pageChange(pageNum: number) {
  queryParams.value.pageNum = pageNum;
  activePager.value = pageNum;
	getInfo();
}

async function sizeChange(sizeNum: number) {
  queryParams.value.pageSize = sizeNum;
	getInfo();
}

const handleUploadImage = (event: Event, insertImage: any, files: File[]) => {
  for (let i in files) {
    const formData = new FormData()
    formData.append('file', files[i])
    axios.post(`${File_API.OTHER_URL}`, formData).then(
      (response) => {
        const { data } = response.data
        insertImage({
          url: data.url,
          desc: 'desc',
        })
      },
      (error) => {
        ElMessage.error(error.message)
      },
    )
  }
}

const update = async (data: QuestionInfo) => {
  try {
    //保证全部表单相校验通过再发请求
    await ruleFormRef.value.validate()
    if (!data.isReward) {
      data.rewardPoints = 0
    }
    data.createTime = ''
    await editQuestion(data)
		getInfo();
    ElMessage.success('修改成功!')
		cloceEditDialog()
  } catch (error) {
    Promise.reject(error)
  }
}


</script>


<style scoped lang="scss">

h1 {
  color: blue;
}
.box {
  display: flex;
  justify-content: center;
  width: 100%;

	.pagination {
  display: flex;
  justify-content: center;
}

.pagination__item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination__item.active {
  color: white;
  background-color: #4593ff;
}


  .main {
    width: 1180px;
    margin: 0px auto;
    border-radius: 8px;
    background-color: white;
    padding: 26px 32px;

    .title {
      font-size: 20px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
}

.pagination__item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination__item.active {
  color: white;
  background-color: #4593ff;
}
</style>

<!-- 饿了么的样式写在这里避免不生效 -->
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #807d7d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 268px;
  height: 178px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 268px;
  height: 178px;
  display: block;
}

.rounded-button {
  display: inline-block;
  padding: 13px 23px 13px 23px; /* 根据需要调整按钮的内边距 */
  border-radius: 17px; /* 设置按钮的圆角半径 */
  background-color: #f0f0f0; /* 设置按钮的背景色 */
  color: #333; /* 设置按钮的文字颜色 */
  font-size: 16px; /* 设置按钮的文字大小 */
  text-decoration: none; /* 去掉按钮的下划线 */
  cursor: pointer; /* 鼠标移上按钮时显示手形光标 */
}

/* 鼠标移上按钮时的样式 */
.rounded-button:hover {
  background-color: #c1daf3; /* 修改按钮的背景色 */
  color: #fff; /* 修改按钮的文字颜色 */
}
</style>
